package com.jiesen.base.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class UploadServletUtils {

    public static JSONObject upload(String url,String name, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
        MultipartFile multipartFile = multiRequest.getFile(name);
        if (!multipartFile.isEmpty()) {
            JSONObject resultJson = sendPost(url, "file", multipartFile,null);
            if (resultJson.getString("code").equals("200")) {
                JSONObject data = resultJson.getJSONObject("data");
                json.put("msg", "上传成功");
                json.put("url", data.getString("url"));
                json.put("result", "OK");
            } else {
                json.put("result", "ERROR");
                json.put("msg", "上传失败检查【图片服务】!!!");
            }
        } else {
            json.put("result", "ERROR");
            json.put("msg", "MultipartFile为空!!!");
        }

        return json;
    }

    public static JSONObject sendPost(String url, String name, MultipartFile file, Map<String,String> params) {
        //创建post请求对象
        HttpPost post = new HttpPost(url);
        String result =null;
        try {
            if(params != null && !params.isEmpty()) {
                //创建参数集合
                List<BasicNameValuePair> list = new ArrayList<>();
                Iterator var = params.entrySet().iterator();
                //添加参数
                //list.add(new BasicNameValuePair(name, ""));
                while(var.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry)var.next();
                    list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
                }

                //把参数放入请求对象，，post发送的参数list，指定格式
                post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            builder.addBinaryBody(name, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());// 文件流

            //添加请求头参数
            post.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18");

            post.setEntity(builder.build());

            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(post);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //把实体对象转换为string
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return JSONObject.parseObject(result);
    }

}
